
package com.nostra13.sample.slice;

import com.nostra13.sample.ResourceTable;
import com.nostra13.sample.bean.ImageFolder;
import com.nostra13.sample.bean.ImageItem;
import com.nostra13.sample.provider.ImageProvider;
import com.nostra13.sample.utils.ResUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.nostra13.universalimageloader.utils.L;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.data.resultset.ResultSet;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ImageAbilitySlice extends AbilitySlice {

    private final String[] IMAGE_PROJECTION = {     //查询图片需要的数据列
            AVStorage.Images.Media.DISPLAY_NAME,   //图片的显示名称  aaa.jpg
            AVStorage.Images.Media.DATA,           //图片的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
            AVStorage.Images.Media.SIZE,           //图片的大小，long型  132492
            //TODO Media.WIDTH  Media.HEIGHT缺失
//            AVStorage.Images.Media.WIDTH,          //图片的宽度，int型  1920
//            AVStorage.Images.Media.HEIGHT,         //图片的高度，int型  1080
            AVStorage.Images.Media.MIME_TYPE,      //图片的类型     image/jpeg
            AVStorage.Images.Media.DATE_ADDED};    //图片被添加的时间，long型  1450518608

    private ResultSet resultSet;
    private ListContainer listContainer;
    private String mPath;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_image);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_listContainer);


        DataAbilityHelper helper = DataAbilityHelper.creator(this);

        new Thread(() -> {
            try {
                if (mPath == null) {
                    resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null);
                } else {
                    resultSet = helper.query(Uri.getUriFromFile(new File(mPath)), null, null);
                }
                getUITaskDispatcher().syncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        onLoadFinished2(resultSet);
//                        L.info("size:" + resultSet.getRowCount());
//                        L.info("size:" + resultSet.getColumnCount());
                    }
                });
            } catch (DataAbilityRemoteException e) {
                Logger.getGlobal().log(Level.INFO, "Exception");
            }
        }).start();
    }

    private void onLoadFinished(ResultSet data) {
        ArrayList<ImageFolder> imageFolders = new ArrayList<>();   //所有的图片文件夹
        if (data != null) {
            ArrayList<ImageItem> allImages = new ArrayList<>();   //所有图片的集合,不分文件夹
            while (data.goToNextRow()) {
                String[] all = data.getAllColumnNames();
                List<String> a = Arrays.asList(all);
                System.out.println("imagepicker log AllColumnNames" + a.toString());
                //查询数据
                String imageName = data.getString(data.getColumnIndexForName(IMAGE_PROJECTION[0]));
                String imagePath = data.getString(data.getColumnIndexForName(IMAGE_PROJECTION[1]));

                File file = new File(imagePath);
                if (!file.exists() || file.length() <= 0) {
                    continue;
                }

                long imageSize = data.getLong(data.getColumnIndexForName(IMAGE_PROJECTION[2]));
                int imageWidth = data.getInt(data.getColumnIndexForName("width"));
                int imageHeight = data.getInt(data.getColumnIndexForName("height"));
                String imageMimeType = data.getString(data.getColumnIndexForName(IMAGE_PROJECTION[3]));
                long imageAddTime = data.getLong(data.getColumnIndexForName(IMAGE_PROJECTION[4]));
                //封装实体
                ImageItem imageItem = new ImageItem();
                imageItem.name = imageName;
                imageItem.path = imagePath;
                imageItem.size = imageSize;
                imageItem.width = imageWidth;
                imageItem.height = imageHeight;
                imageItem.mimeType = imageMimeType;
                imageItem.addTime = imageAddTime;
                allImages.add(imageItem);
                System.out.println("imagepicker log imageItem" + imageItem.toString());

                //根据父路径分类存放图片
                File imageFile = new File(imagePath);
                File imageParentFile = imageFile.getParentFile();
                ImageFolder imageFolder = new ImageFolder();
                imageFolder.name = imageParentFile.getName();
                try {
                    imageFolder.path = imageParentFile.getCanonicalPath();
                } catch (IOException e) {
                   Logger.getGlobal().log(Level.INFO,"IOException");
                }
                if (!imageFolders.contains(imageFolder)) {
                    ArrayList<ImageItem> images = new ArrayList<>();
                    images.add(imageItem);
                    imageFolder.cover = imageItem;
                    imageFolder.images = images;
                    imageFolders.add(imageFolder);
                } else {
                    imageFolders.get(imageFolders.indexOf(imageFolder)).images.add(imageItem);
                }
            }
            //防止没有图片报异常
            if (data.getColumnCount() > 0 && allImages.size() > 0) {
                //构造所有图片的集合
                ImageFolder allImagesFolder = new ImageFolder();
                allImagesFolder.name = ResUtil.getString(this, ResourceTable.String_ip_all_images);
                allImagesFolder.path = "/";
                allImagesFolder.cover = allImages.get(0);
                allImagesFolder.images = allImages;
                imageFolders.add(0, allImagesFolder);  //确保第一条是所有图片
            }
        }
        L.info("size=" + imageFolders.size());
        listContainer.setItemProvider(new ImageProvider(this, imageFolders));
        listContainer.setScrolledListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true));
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Intent secondIntent = new Intent();
                secondIntent.setParam("url", imageFolders.get(i).path);
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.nostra13.sample")
                        .withAbilityName("com.nostra13.sample.DetailAbility")
                        .build();
                secondIntent.setOperation(operation);
                startAbility(secondIntent);
            }
        });
    }

    private ArrayList<ImageFolder> imageFolders = new ArrayList<>();   //所有的图片文件夹
    public void onLoadFinished2(ResultSet data) {
        imageFolders.clear();
        if (data != null) {
            ArrayList<ImageItem> allImages = new ArrayList<>();   //所有图片的集合,不分文件夹
            while (data.goToNextRow()) {
                String[] all = data.getAllColumnNames();
                List<String> a = Arrays.asList(all);
                System.out.println("imagepicker log AllColumnNames" + a.toString());
                //查询数据
                String imageName = data.getString(data.getColumnIndexForName(IMAGE_PROJECTION[0]));
                String imagePath = data.getString(data.getColumnIndexForName(IMAGE_PROJECTION[1]));
                int id = data.getInt(data.getColumnIndexForName(AVStorage.Images.Media.ID));
                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));

                File file = new File(imagePath);
                if (!file.exists() || file.length() <= 0) {
                    continue;
                }

                long imageSize = data.getLong(data.getColumnIndexForName(IMAGE_PROJECTION[2]));
                int imageWidth = data.getInt(data.getColumnIndexForName("width"));
                int imageHeight = data.getInt(data.getColumnIndexForName("height"));
                String imageMimeType = data.getString(data.getColumnIndexForName(IMAGE_PROJECTION[3]));
                long imageAddTime = data.getLong(data.getColumnIndexForName(IMAGE_PROJECTION[4]));
                //封装实体
                ImageItem imageItem = new ImageItem();
                imageItem.name = imageName;
                imageItem.path = imagePath;
                imageItem.size = imageSize;
                imageItem.width = imageWidth;
                imageItem.height = imageHeight;
                imageItem.mimeType = imageMimeType;
                imageItem.addTime = imageAddTime;
                imageItem.uri = uri;
                allImages.add(imageItem);
                System.out.println("imagepicker log imageItem" + imageItem.toString());

                //根据父路径分类存放图片
                File imageFile = new File(imagePath);
                File imageParentFile = imageFile.getParentFile();
                ImageFolder imageFolder = new ImageFolder();
                imageFolder.name = imageParentFile.getName();
                try {
                    imageFolder.path = imageParentFile.getCanonicalPath();
                } catch (IOException e) {
                    Logger.getGlobal().log(Level.INFO,"IOException");
                }
                if (!imageFolders.contains(imageFolder)) {
                    ArrayList<ImageItem> images = new ArrayList<>();
                    images.add(imageItem);
                    imageFolder.cover = imageItem;
                    imageFolder.images = images;
                    imageFolders.add(imageFolder);
                } else {
                    imageFolders.get(imageFolders.indexOf(imageFolder)).images.add(imageItem);
                }
            }
            //防止没有图片报异常
            if (data.getColumnCount() > 0 && allImages.size() > 0) {
                //构造所有图片的集合
                ImageFolder allImagesFolder = new ImageFolder();
                allImagesFolder.name = ResUtil.getString(this, ResourceTable.String_ip_all_images);
                allImagesFolder.path = "/";
                allImagesFolder.cover = allImages.get(0);
                allImagesFolder.images = allImages;
                imageFolders.add(0, allImagesFolder);  //确保第一条是所有图片
            }
        }

        L.info("size=" + imageFolders.size());
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
